package leetcode.list;

import utils.node.ListNode;

/**
 * @Description: https://leetcode.cn/problems/palindrome-linked-list/
 * @Author Ammar
 * @Create 2023/7/11 10:42
 */
public class _234_回文链表 {

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) return true;
        if (head.next.next == null) return head.val == head.next.val;

        // 找到中间节点
        ListNode mid = middleNode(head);
        // 翻转中间节点的右边部分
        ListNode rHead = reverseList(mid.next);
        ListNode lHead = head;
        while (rHead != null) {
            if (lHead.val != rHead.val) {
                // 如果要求不破坏原来链表
//                reverseList(rHead);
//                mid.next = rHead;
                return false;
            }
            rHead = rHead.next;
            lHead = lHead.next;
        }

        // 如果要求不破坏原来链表
//        reverseList(rHead);
//        mid.next = rHead;
        return true;
    }

    // 找到中间节点 快慢指针
    private ListNode middleNode(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    // 反转链表
    private ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode newHead = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = newHead;
            newHead = head;
            head = temp;
        }
        return newHead;
    }
}
